import React, { useEffect, useRef, useState } from "react";
import "./style.scss";
import { Input } from "antd-mobile";

const user_id = 1;
const server_id = 123456;
const ws = new WebSocket(
  `ws://124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
);

const Chat = () => {
  const [list, setList] = useState([]);
  useEffect(() => {
    ws.addEventListener("open", () => {
      console.log("WebSocket connected");

      ws.send(
        JSON.stringify({
          type: "getChatList",
          data: { user_id, server_id },
        })
      );
    });

    ws.addEventListener("message", (e) => {
      const { type, data } = JSON.parse(e.data);
      if (type === "getChatList") {
        setList(data);
      } else if (type === "addMessage") {
        setList((prev) => [...prev, data]);
      }
    });
  }, []);

  const onKeyDown = (e) => {
    if (e.keyCode === 13) {
      const message = e.target.value;
      if(message === "") {
        alert('消息不可以为空！！！')
        return ;
      }
      ws.send(
        JSON.stringify({
          type: "addMessage",
          data: { user_id, server_id, message },
        })
      );
    }
  };


  const refEl = useRef()
  useEffect(() => {
    // chatRef.scrollTop = 10000000000

    refEl.current.scrollTop = 10000000000
  }, [list])

  return (
    <div>
      <div className="chat-list" id="chatRef" ref={refEl}>
        {list.map((v, i) => {
          const myClassName =
            v.dir === 1 ? "chat-list-right" : "chat-list-left";
          const avatar = v.dir === 1 ? v.user_avatar : v.server_avatar;
          return (
            <div className={myClassName} key={i}>
              <img src={avatar} alt="" className="avatar" />
              <div className="content">{v.message}</div>
            </div>
          );
        })}

        <Input
          style={{
            position: "fixed",
            left: 0,
            bottom: 0,
            width: "100%",
            background: 'white',
            height: 50
          }}
          placeholder="请输入消息"
          onKeyDown={(e) => onKeyDown(e)}
        ></Input>
      </div>
    </div>
  );
};

export default Chat;
